package com.weme.chat.view

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View.OnFocusChangeListener
import android.widget.FrameLayout
import com.weme.chat.ChatActivity
import com.weme.chat.databinding.ViewChatInputBinding
import com.weme.common.util.*
import com.weme.common.view.CustomDialogFragment
import io.agora.chat.ChatClient
import io.agora.chat.ChatMessage
import io.agora.chat.ChatMessage.Direct
import io.agora.chat.CmdMessageBody


interface ChatInputListener {


    fun onTextEntered(text: String)
    fun onImageEntered(text: String)
    fun onShowGiftDialog()

    fun isMax2Msg():Boolean
}

class ViewChatInput @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0) : FrameLayout(context, attributeSet, defStyle) {
    private var chatInputListener: ChatInputListener? = null
    private val viewBinding = ViewChatInputBinding.inflate(LayoutInflater.from(context), this, true)
    var time = 5000 //按照自己的需求自定义时间间隔发送状态消息（单位：ms）
    val maxLength = 140

    var firstTime = System.currentTimeMillis() //文本框第一次输入内容变化的时间

    init {
        viewBinding.imSendImg.setOnFastClickListener {
            if(context.isVip()){
                //男包不可以发图片  要显示个dialog
                val dialog = CustomDialogFragment.newInstance(title = "", content = context.getString(com.example.resources.R.string.chat_image_error),
                    positiveButtonText = context.getString(com.example.resources.R.string.ok), negativeButtonText = "", listener = object : CustomDialogFragment.DialogClickListener {
                        override fun onPositiveButtonClick() {

                        }

                        override fun onNegativeButtonClick() {


                        }
                    })
                dialog.show((context as ChatActivity).supportFragmentManager, "CustomDialog")
            }else{
                context.showToast("跳转到订阅商城")
            }




//            if(isSendMsg()) {
//                MediaUtils.selectImages(UtilsApp.getTopActivity(), 1) {
//                    (context as ChatActivity).alertDialog?.show()
//                    chatInputListener?.onImageEntered(it)
//                }
//            }
        }
        viewBinding.imSendGift.setOnFastClickListener {
            chatInputListener?.onShowGiftDialog()

        }

        viewBinding.edInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (s.length > maxLength) { // 如果输入字符数量超过最大限制，则截取前面的 MAX_CHARACTERS 个字符
                    val truncatedText = s.toString().substring(0, maxLength) // 更新输入框的文本
                    viewBinding.edInput.setText(truncatedText) // 将光标移动到文本末尾
                    viewBinding.edInput.setSelection(maxLength)
                    context.showToast(context.resources.getString(com.example.resources.R.string.live_max_characters_exceeded))

                } else if (System.currentTimeMillis() - firstTime > time) {
                    sendInputmsg(AgoraClient.ACTION_TYPING_INPUT)
                    firstTime = System.currentTimeMillis()
                }
            }

            override fun afterTextChanged(s: Editable) {
                viewBinding.ibSend.alpha = if (viewBinding.edInput.text.toString().isNotEmpty()) 1F else 0.6F
            }
        })

        viewBinding.edInput.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
            if (!hasFocus) {
                sendInputmsg(AgoraClient.ACTION_TYPING_INPUT_END)
            }
        }
        viewBinding.ibSend.setOnFastClickListener {
            sendInputmsg(AgoraClient.ACTION_TYPING_INPUT_END)
            if(isSendMsg()) {
                chatInputListener?.onTextEntered(viewBinding.edInput.text.toString().trim())
            }
            viewBinding.edInput.text.clear()
        }
    }

    var conversationId: String = ""
    fun sendInputmsg(action: String) {
            val cmdMsg = ChatMessage.createSendMessage(ChatMessage.Type.CMD)
            val cmdBody = CmdMessageBody(action)
            cmdBody.deliverOnlineOnly(true)
            cmdMsg.addBody(cmdBody)
            cmdMsg.to = conversationId
            ChatClient.getInstance().chatManager().sendMessage(cmdMsg)
            cmdMsg.chatType = ChatMessage.ChatType.Chat
            return

    }

    fun isSendMsg():Boolean{
        if(!context.isVip()){
            context.showToast("跳转到订阅商城")
            return false
        }else if(chatInputListener!!.isMax2Msg()){
            val dialog = CustomDialogFragment.newInstance(title = "", content = context.getString(com.example.resources.R.string.chat_send_error),
                positiveButtonText = context.getString(com.example.resources.R.string.ok), negativeButtonText = "", listener = object : CustomDialogFragment.DialogClickListener {
                    override fun onPositiveButtonClick() {

                    }

                    override fun onNegativeButtonClick() {


                    }
                })
            dialog.show((context as ChatActivity).supportFragmentManager, "CustomDialog")
            return false
        }
        return true
    }

    fun setChatInputListener(listener: ChatInputListener, conversationId: String) {
        chatInputListener = listener
        this.conversationId = conversationId
    }
    fun setKeyboardVisibilityChanged(isVisible: Boolean){
        if(!isVisible){
            viewBinding.edInput.clearFocus()
        }
    }





    fun removeChatInputListener() {
        viewBinding.edInput.removeTextChangedListener(null)
        chatInputListener = null

    }

}